#include "ParameterInput.h"
#include "support.h"
#include <QBoxLayout>
#include <QLabel>

ParameterInput::ParameterInput(int rows, int cols, int type, int minValue, int maxValue, const QString &filterName) : Filter(0, 1), rows(rows), cols(cols), name(filterName)
{
	propertiesWidget = new QWidget(nullptr);
	layout = new QGridLayout(nullptr);
	sliders = new QSlider*[rows * cols];
	converters = new IntStringConverter*[rows * cols];
	outputs[0] = cv::Mat(rows, cols, type);
	value = cv::Mat(rows, cols, type);

	for (int i = 0; i < rows * cols; ++i)
	{
		sliders[i] = new QSlider(Qt::Vertical);
		sliders[i]->setMaximum(maxValue);
		sliders[i]->setMinimum(minValue);
		//sliders[i]->setTracking(false);

		QLabel *label = new QLabel();
		label->setText(QString::number(sliders[i]->value()));
		converters[i] = new IntStringConverter(nullptr);

		QObject::connect(sliders[i], SIGNAL(valueChanged(int)), converters[i], SLOT(IntIn(const int &)));
		QObject::connect(converters[i], SIGNAL(StringOut(const QString &)), label, SLOT(setText(const QString &)));

		QHBoxLayout *sliderLayout = new QHBoxLayout();
		sliderLayout->addWidget(sliders[i]);
		sliderLayout->addWidget(label);

		layout->addLayout(sliderLayout, i / cols, i % cols, 1, 1);

		QObject::connect(sliders[i], SIGNAL(valueChanged( int )), this, SLOT(newValue()));
	}
	newValue();
	propertiesWidget->setLayout(layout);
}


ParameterInput::~ParameterInput(void)
{
	delete propertiesWidget;
	delete [] sliders;
	delete [] converters;
}

void ParameterInput::newValue()
{
	valueMutex.lock();
	for (int i = 0; i < rows; ++i)
	{
		int *p = value.ptr<int>(i);
		for (int j = 0; j < cols; ++j)
		{
			p[j] = sliders[i*cols + j]->value();
		}
	}

	valueMutex.unlock();
}

void ParameterInput::Process()
{
	QSize s = propertiesWidget->size();

	valueMutex.lock();
	outputs[0] = value;
	valueMutex.unlock();
}

QWidget *ParameterInput::GetPropertiesWidget()
{
	return propertiesWidget;
}

QString ParameterInput::GetFilterName()
{
	if (name.length())
		return name;
	else
		return Filter::GetFilterName();
}
